package cn.iotab.iotkit.transport.api.access.model.custom.property;

import cn.iotab.iotkit.transport.api.access.model.custom.ProtocolConstant;
import cn.iotab.iotkit.transport.api.access.model.message.CommonDeviceMessage;
import cn.iotab.iotkit.transport.api.access.model.message.OriginMessage;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.Getter;
import lombok.Setter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 修改属性指令,方向: 平台->设备
 * <p>
 * 用于修改设备属性,下发指令后,设备需要回复{@link PropertyPushMessageReply}
 *
 * @author zhouhao
 * @since 1.0.0
 */
@Getter
@Setter
public class PropertyPushMessage extends CommonDeviceMessage {

    /**
     * property后缀，拼接在prop.后面
     */
    private String propertySuffix;
    /**
     * 要修改的属性，key 为物模型中对应的属性ID,value为属性值
     */
    private Map<String, Object> properties = new LinkedHashMap<>();

    public PropertyPushMessage addProperty(String key, Object value) {
        properties.put(key, value);
        return this;
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

    @Override
    public void fromOriginMessage(String productKey, String deviceId, OriginMessage message) {
        super.fromOriginMessage(productKey, deviceId, message);
        propertySuffix = getOriginType().substring(ProtocolConstant.PROP_PREFIX.length());
        properties = getJsonParam().toJavaObject(new TypeReference<Map<String, Object>>() {
        });
    }

    @Override
    public OriginMessage toOriginMessage() {
        if (propertySuffix == null || propertySuffix.isEmpty()) {
            throw new IllegalArgumentException("propertySuffix is null or empty");
        }
        String tp = ProtocolConstant.PROP_PREFIX + propertySuffix;
        setOriginType(tp);
        JSONObject object = new JSONObject();
        object.putAll(properties);
        setJsonParam(object);
        return super.toOriginMessage();
    }


}
